package com.tools.starter.swagger.sqlite;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author com.tools
 * @version 1.0
 * @Description: SQLiteHelper
 * <com.tools.starter.swagger.sqlite>
 * @date Created in 2020/8/27 18:04
 **/
@Slf4j
@Component
@EnableConfigurationProperties(SQLiteProperties.class)
public class SQLiteHelper {

    @Autowired
    private SQLiteProperties sqLiteProperties;
    private static String CLASS_NAME= "org.sqlite.JDBC";

    private final static String REPLICATE_URL_PREFIX = "jdbc:sqlite:%s";

    public Connection buildDataSource() {
        Connection c = null;
        try {
            existOrCreateDirectory(sqLiteProperties.getPath());
            Class.forName("org.sqlite.JDBC");
            c = DriverManager.getConnection(String.format(REPLICATE_URL_PREFIX, sqLiteProperties.getPath()  +sqLiteProperties.getDbName()));
        } catch (ClassNotFoundException e) {
            log.error("load data source class error, class name is :{} ",CLASS_NAME);
        } catch (SQLException s) {
            log.error("get data source connection error, connection url is :{}",sqLiteProperties.getPath());
        }
        return c;
    }

    private void existOrCreateDirectory(String path) {
        File file =new File(path);
        if  (!file .exists()  && !file .isDirectory())
        {
            file .mkdirs();
        }
    }
}
